Chapter 20: Deleting a Todo
We are currently just rendering a delete button for each todo in todos-list.js:
Analyze Code
<Button variant="outline-danger">
Delete
</Button>
Let ’ s now implement its functionality by adding the below in bold:
Modify Bold Code
…
<Button variant="outline-danger" onClick={() => deleteTodo(todo.id)}>
Delete
</Button>
…
Next, add in the codes for deleteTodo just above return:
Modify Bold Code
…
const deleteTodo = (todoId) =>{
TodoDataService.deleteTodo(todoId, props.token)
.then(response => {
retrieveTodos();
})
.catch(e =>{
console.log(e);
});
}
return (
<Container>
…
Code Explanation
Analyze Code
<Button variant="outline-danger" onClick={() => deleteTodo(todo.id)}>
In the delete button, we pass in todo id into deleteTodo.
In deleteTodo, we then call deleteTodo in TodoDataService which calls the delete API endpoint we implemented
earlier:
Analyze Code
deleteTodo(id, token){
axios.defaults.headers.common["Authorization"] = "Token " + token;
return axios.delete(`http://localhost:8000/api/todos/${id}`);
}
Remember that the delete endpoint is supported by TodoRetrieveUpdateDestroy view in todobackend/api/views.py:
Analyze Code
class TodoRetrieveUpdateDestroy(generics.RetrieveUpdateDestroyAPIView):
serializer_class = TodoSerializer
permission_classes = [permissions.IsAuthenticated]
def get_queryset(self):
user = self.request.user
# user can only update, delete own posts
return Todo.objects.filter(user=user)
Back in todos-list.js, we then add a callback function that is called when deleteTodo completes:
Analyze Code
const deleteTodo = (todoId) =>{
TodoDataService.deleteTodo(todoId, props.token)
.then(response => {
retrieveTodos();
})
.catch(e =>{
console.log(e);
});
}